# 要备份的数据集
backup_dataset=
# 开始快照，如果不提供，表示完整备份
start_snap=
# 结束快照，如果不提供，表示到最新的快照
end_snap=

# 是否递归子数据集标志
r_flag=
# 显示进度标志
v_flag=
# 增量标志
i_flag=""

# 目标主机
target_host=
# 目标主机端口
target_port=8023

# 异常信息
function fatal (){
        echo "$1"
        exit 1
}

# 获取数据集最后的快照名称
# 如果数据集不存在或没有快照，则返回""
function get_latest_snapshot(){
    local ds=$1
    local ss_name=$(zfs list -o name -rt snapshot ${ds} 2>/dev/null | tail -n 1 | cut -d '@' -f 2)
    [[ "${ss_name}" == "no datasets available" ]] && ss_name=""
    echo ${ss_name}
}


# 读取参数
while [[ $# -ge 1 ]]; do
    case $1 in
        -d )
            backup_dataset=$2
            shift 2
            ;;
        -th )
            target_host=$2
            shift 2
            ;;  
        -tp )
            target_port=$2
            shift 2
            ;;               
        -s )
            start_snap=$2
            shift 2
            ;;
        -e )
            end_snap=$2
            shift 2
            ;;
        -r )
            r_flag=" -R"
            shift
            ;;
        -v )
            v_flag=" -v"
            shift
            ;;
        * )
            echo ""
            echo "not supported arg: $1"
            echo ""
            exit 1
            ;;
    esac
done



[[ "${target_host}" != "" ]] || fatal "必须提供目标主机"

[[ "${backup_dataset}" != "" ]] || fatal "必须提供要备份的数据集"

if [ "${end_snap}" == "" ]; then
    end_snap=$(get_latest_snapshot ${backup_dataset})
    [[ "${end_snap}" != "" ]] || fatal "数据集 ${backup_dataset} 不存在快照"
fi

if [ "${start_snap}" != "" ]; then
        i_flag=" -I ${backup_dataset}@${start_snap}"
        zfs list ${backup_dataset}@${start_snap} || fatal "不存在数据集或开始快照"
fi

zfs list ${backup_dataset}@${end_snap} || fatal "不存在数据集或结束快照"

echo "zfs send ${v_flag}${r_flag}${i_flag} ${backup_dataset}@${end_snap} | nc -w 20 ${target_host} ${target_port}"
zfs send ${v_flag}${r_flag}${i_flag} ${backup_dataset}@${end_snap} | nc -w 20 ${target_host} ${target_port}
